package com.mind.db.async.model;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import com.mind.db.IEntity;
import com.mind.db.async.model.AsyncBean.OperationType;


/**
 * 数据库更新队列
 * ---blockingQueue队列长度可能会大于entities
 * 
 * @author yangshaobo 2012-5-17
 */
public class DBUpdateQueue {
	/** 多线程---线程安全*/
	private  BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>(10000);
	/** 多线程---线程安全*/
	private Map<String, AsyncBean> entities=new ConcurrentHashMap<String, AsyncBean>(10000);
	public  void create(IEntity entity) {
		blockingQueue.add(entity.getClass().getSimpleName()+entity.getId());
		entities.put(entity.getClass().getSimpleName()+entity.getId(), new AsyncBean(OperationType.CREATE, entity));
	}
	public  void update(IEntity entity) {
		String key=entity.getClass().getSimpleName()+"#"+entity.getId();
		if(!blockingQueue.contains(key)){
			blockingQueue.add(key);
		}
		entities.put(key, new AsyncBean(OperationType.UPDATE, entity));
	}
	public  AsyncBean pop() {
		String id=blockingQueue.poll();
		return entities.get(id);
	}
	public  int size() {
		return blockingQueue.size();
	}
	public  int realSize() {
		return entities.size();
	}
}
